﻿#include<iostream>
using namespace std;

class Rate
{
public:
	Rate(double rate)
		: _rate(rate)
	{}
	double operator()(double money, int year)
	{
		return money * _rate * year;
	}
private:
	double _rate;
};

int x = 0;
auto func1 = []()
	{
		x++;
	};

int main()
{
	double rate = 0.49;
	
	//lambda
	auto r2 = [rate](double money, int year) {
		return money * rate * year;
		};

	// 函数对象
	Rate r1(rate);
	r1(10000, 2);
	r2(10000, 2);

	int a = 0, b = 1, c = 2, d = 3;
	auto func1 = [a, &b] {
		//值捕捉的变量不能修改，引用捕捉的变量可以修改
		b++;
		//a++;
		int ret = a + b;
		return ret;
		};
	

	// 局部的静态和全局变量不能捕捉，也不需要捕捉
	static int m = 0;
	auto func6 = []
		{
			int ret = x + m; //x为全局变量，m为静态局部变量
			return ret;
		};

	cout << func1() << endl;

	// 隐式引⽤捕捉
   // 用了哪些变量就捕捉哪些变量
	auto func3 = [&] {
		a++;
		b++;
		c++;
		return a + b + c;
		};
	cout << func3() << endl;
	cout << a << " " << b << " " << c << " " << d << endl;

	// 混合捕捉1
	auto func4 = [&, a, b]
		{
			//a++;
			//b++;
			c++;
			d++;
			return a + b + c + d;
		};
	func4();
	cout << a << " " << b << " " << c << " " << d << endl;

	// 混合捕捉2
	auto func5 = [=, &a, &b]
		{
			a++;
			b++;
			/*c++;
			d++;*/
			return a + b + c + d;
		};
	func5();
	cout << a << " " << b << " " << c << " " << d << endl;

	// 传值捕捉本质是⼀种拷⻉,并且被const修饰了
   // mutable相当于去掉const属性，可以修改了
   // 但是修改了不会影响外⾯被捕捉的值，因为是⼀种拷⻉
	auto func7 = [=]()mutable
		{
			a++;
			b++;
			c++;
			d++;
			return a + b + c + d;
		};
	cout << func7() << endl;
	cout << a << " " << b << " " << c << " " << d << endl;

	return 0;
}